package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.dpmain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Activity;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.RoleService;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @文件名: UserServiceImpl
 * @作者: DX
 * @创建日期: 2025/10/7
 * @描述:
 */
@Service
public class UserServiceImpl implements UserService {

    private static final String DEFAULT_PASSWORD_SUFIX = "123";
    private static final Integer USER_STATUS_UNNORMAL = 0;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Override
    public UserLoginVO login(UserLoginDTO dto) {

        if (BeanUtil.hasNullField(dto)){
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
        }

        User user = userMapper.getByUsername(dto.getUsername());

        if (Objects.isNull(user)){
            CommonException.thowsCommonException(ParamEnum.USER_LOGIN_ERROR);
        }

        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()) ;

        if (ObjectUtil.equal(USER_STATUS_UNNORMAL, user.getStatus())){
            CommonException.thowsCommonException(ParamEnum.LOGIN_STATUS_ERROR);
        }

        if (!ObjectUtil.equal(user.getPassword(), userPassword)){
            CommonException.thowsCommonException(ParamEnum.USER_PASSWORD_ERROR);
        }

        Role role = roleService.getById(user.getRoleId());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        String token = JwtUtils.generateToken(claims);

        return UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .image(user.getImage())
                .roleLabel(role.getLabel())
                .token( token)
                .build();
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        if (!CollectionUtil.isNotEmpty(ids)){
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
        }
        userMapper.deleteByIds(ids);

    }
    @Override
    public List<Activity> listByRole(String roleLabel) {
        if (roleLabel == null || roleLabel.isEmpty()){
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
        }
        return userMapper.listByRole(roleLabel);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }


    @Override
    public void add(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull){
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
        }

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String rawPassword = new StringBuffer(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        String encryptedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encryptedPassword);
        userMapper.insert(user);
    }

    @Override
    public PageResult<UserDO> list(UserDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<UserDO> result =  userMapper. selectByPage(dto);

        result.stream().forEach(userDO -> {
            userDO.setPhone(PhoneUtil.hideBetween(userDO.getPhone()).toString());
        });

        Page<UserDO> page = (Page<UserDO>) result;

        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
